package com.sj.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sj.entity.Blog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author 小七
 * @since 2021-07-30
 */
@Repository
public interface BlogMapper extends BaseMapper<Blog> {


    /**
     * 分页查询博客列表
     *
     * @param page 分页条件
     * @param blog 查询条件
     * @return
     */
    IPage<Blog> listBlogByPage(IPage<Blog> page, Blog blog);

    /**
     * 绑定博客与标签
     *
     * @param wantBindBlogTagIds 需要绑定到博客上的标签id
     * @param blogId             博客id
     * @return 是否成功
     */
    Integer bindTags(@Param("tagIdList") ArrayList<Integer> wantBindBlogTagIds, @Param("blogId") Integer blogId);

    /**
     * 判断标签是否与博客绑定
     *
     * @param tagId  标签id
     * @param blogId 博客id
     * @return 是否绑定
     */
    @Select("select count(*) from blog_tag where tag_id = #{tagId} and blog_id = #{blogId}")
    Integer tagIsBindBlog(@Param("tagId") Integer tagId, @Param("blogId") Integer blogId);

    /**
     * 删除博客所有的标签
     *
     * @param blogId 博客id
     * @return 删除条数
     */
    @Delete("delete from blog_tag where blog_id = #{blogId}")
    Integer deleteBlogAllTags(Integer blogId);

    /**
     * 解除标签和博客的绑定
     *
     * @param tagId  标签id
     * @param blogId 博客id
     * @return 是否成功
     */
    @Delete("delete from blog_tag where blog_id = #{blogId} and tag_id = #{tagId}")
    Integer deleteTagBindBlog(@Param("tagId") Integer tagId, @Param("blogId") Integer blogId);


    /**
     * 查询博客详情
     *
     * @param blogId     博客id
     * @param publicType 公开类型
     * @param userId     用户id
     * @return 博客详情
     */
    @Select("<script>" +
            "select * from blog where id = #{blogId} and status = 1" +
            "<if test='publicType != null '>" +
            " and public_type = #{publicType}" +
            "</if>" +
            "<if test='userId != null '>" +
            " and user_id = #{userId}" +
            "</if>" +
            "</script>")
    @Results({
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "category_id", property = "category", one = @One(select = "com.sj.mapper.CategoryMapper.selectById", fetchType = FetchType.EAGER)),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "user_id", property = "user", one = @One(select = "com.sj.mapper.UserMapper.getUserById", fetchType = FetchType.EAGER))
    })
    Blog getBlogDetail(@Param("blogId") Integer blogId, @Param("publicType") Integer publicType, @Param("userId") Integer userId);


}
